﻿using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using System.Xml.Linq;

namespace EasyXaf.EntityDesigner.Editors.DetailViewEditors.Models;

/// <summary>
/// 布局设计器
/// </summary>
public class LayoutDesigner
{
    /// <summary>
    /// 主面板
    /// </summary>
    public Panel MainPanel { get; private set; }

    /// <summary>
    /// 实体
    /// </summary>
    public Entity Entity { get; }

    public event EventHandler LayoutChanged;

    public LayoutDesigner(Entity entity)
    {
        Entity = entity;
        ResetMainPanel();
    }

    private void ResetMainPanel()
    {
        MainPanel = new Panel(null, this)
        {
            LayoutDirection = LayoutDirection.Vertical,
            IsRoot = true,
        };
    }

    public Component FindComponent(Guid componentId)
    {
        if (MainPanel.Oid == componentId)
        {
            return MainPanel;
        }
        return MainPanel.FindComponent(componentId);
    }

    public void RaiseLayoutChanged()
    {
        LayoutChanged?.Invoke(this, EventArgs.Empty);
    }

    public string ToXml()
    {
        var elementName = MainPanel.LayoutDirection == LayoutDirection.Horizontal ? "h" : "v";
        var panelElement = new XElement(elementName);
        MainPanel.WriteToXml(panelElement);
        return panelElement.ToString();
    }

    public void FromXml(string xml)
    {
        if (!string.IsNullOrWhiteSpace(xml))
        {
            var panelElement = XElement.Parse(xml);
            MainPanel.ReadFromXml(panelElement);
        }
        else
        {
            ResetMainPanel();
        }
    }
}
